using System.Data.SqlClient;
using NUnit.Framework;
using TDUnit.Loggers;
using TDUnit.MsSql;
using TDUnit.TestDataParsers.XmlParser;

namespace TDUnit.Examples
{
    public abstract class SqlServerTestDataTestsBase
    {
        protected SqlServerTestDataUtility testDataUtility;
        protected Common.TestData.TestData dataset;

        protected virtual string GetDataSetNamespace()
        {
            return string.Empty;
        }

        protected virtual string GetTestDataString()
        {
            return string.Empty;
        }

        protected virtual string GetTestDataFilePath()
        {
            return string.Empty;
        }

        [SetUp]
        public void SetUp()
        {
            var parser = new XmlTestDataParser { TestDataString = GetTestDataString(), TestDataFilePath = GetTestDataFilePath() };
            testDataUtility = new SqlServerTestDataUtility(connectionString, parser, new FileLogger());
            dataset = testDataUtility.SetUp();
        }

        [TearDown]
        public void TearDown()
        {
            testDataUtility.TearDown();
        }

        protected const string connectionString =
            @"Server=.\SQLExpress;Database=TDUnitScriptExecutionTests; Trusted_Connection=Yes;";

        protected static object ExecuteScalarQuery(string query)
        {
            object data;
            using (var connection = new SqlConnection(connectionString))
            {
                connection.Open();
                using (var cmd = new SqlCommand(query, connection))
                {
                    data = cmd.ExecuteScalar();
                }
            }
            return data;
        }

        protected static void ExecuteNonQuery(string statement)
        {
            using (var connection = new SqlConnection(connectionString))
            {
                connection.Open();
                using (var cmd = new SqlCommand(statement, connection))
                {
                    cmd.ExecuteNonQuery();
                }
            }
        }
    }
}